package com.yaolaizaixian.merchant;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.yanzhenjie.permission.AndPermission;
import com.yaolaizaixian.merchant.base.BaseActivity;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.home.Fragment_home;
import com.yaolaizaixian.merchant.home.Fragment_mune;
import com.yaolaizaixian.merchant.home.RightsActivity;
import com.yaolaizaixian.merchant.utils.MyNetUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.yaolaizaixian.merchant.utils.UpdateManager;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;

public class HomeActivity extends BaseActivity {

    public static final String LEFT_MENU = "left_menu";
    public static List<String> logList = new CopyOnWriteArrayList<String>();
    @BindView(R.id.rl_cehua)
    AutoRelativeLayout rlCehua;
    @BindView(R.id.rl_quanyi)
    AutoRelativeLayout rlQuanyi;
    @BindView(R.id.fl_home)
    FrameLayout flHome;
    private SlidingMenu slidingMenu;
    private static final String TAG = "HomeActivity";
    private AlertDialog.Builder conflictBuilder;
    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:

                    String result = (String) msg.obj;

                    break;
            }
        }
    };

    @Override
    public void initView() {

        setContentView(R.layout.activity_main);

    }

    @Override
    public void initData() {

        String cid = SharedPreferencesUtil.getString(getApplicationContext(), "cid", "");
        Log.e(TAG, cid);
        PostCid(cid);

        //获取权限   读取sd卡  读取地址  获取照相机  获取地理位置
        AndPermission.with(this)
                .requestCode(101)
                .permission(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                        , Manifest.permission.CAMERA, Manifest.permission.LOCATION_HARDWARE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
                        , Manifest.permission.READ_PHONE_STATE)
                .send();

        //判断版本号
        new UpdateManager(this).checkUpdate(getApplicationContext());

        initmune();

        // 调用 JPush 接口来设置别名。
        JPushInterface.setAliasAndTags(getApplicationContext(),
                "lifeShop" + SharedPreferencesUtil.getString(getApplicationContext(), "usersysno", ""),
                null,
                null);

        Log.e(TAG, "极光别名====lifeShop" + SharedPreferencesUtil.getString(getApplicationContext(), "usersysno", ""));

        //小米增量更新(//第二个参数为true时使用沙盒环境，否则使用线上环境)
        //XiaomiUpdateAgent.update(this, true);
        ////这种情况下, 若本地版本是debug版本则使用沙盒环境，否则使用线上环境
        //XiaomiUpdateAgent.update(this);
    }

    //上传cid到服务器
    private void PostCid(String cid) {

        try {

            HashMap<String, String> sortedParams = new HashMap<String, String>();
            // sysNo 值  3des加密
            final String url = BaseInfo.URL + "push/registrationPush.do";
            //员工或客户id
            sortedParams.put("userSysno", SharedPreferencesUtil.getString(getApplicationContext(), "usersysno", ""));
            //推送注册id
            sortedParams.put("registrationId", cid);
            //设备类型(1：android 2:ios)
            sortedParams.put("deviceType", "1");
            //推送类型(1:员工 2:客户)
            sortedParams.put("pushType", "3");
            //别名（lifeShop+员工或客户id 比如:lifeShop116）
            sortedParams.put("alias", "lifeShop" + SharedPreferencesUtil.getString(getApplicationContext(), "usersysno", ""));
            Log.e(TAG, "CID" + cid);
            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, getApplicationContext()))
                    .build()
                    .execute(new MyStringCallback());

        } catch (Exception e) {

            e.printStackTrace();
        }

    }

    @OnClick({R.id.rl_cehua, R.id.rl_quanyi})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_cehua:

                if (null != slidingMenu) {
                    slidingMenu.toggle();
                }

                break;
            case R.id.rl_quanyi:
                  //权益列表
                startActivity(new Intent(HomeActivity.this, RightsActivity.class));

                break;
        }
    }

    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {

        }

        @Override
        public void onResponse(String response, int id) {

            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mhandler.sendMessage(message);
        }

    }

    private void initmune() {

        //替换主界面内容
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_home, new Fragment_home()).commit();
        //实例化菜单控件
        slidingMenu = new SlidingMenu(this);
        //设置相关属性
        slidingMenu.setMode(SlidingMenu.LEFT);//菜单靠左
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);//全屏支持触摸拖拉
        WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        slidingMenu.setBehindOffset(width / 3);//设置菜单大小
        slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);//不包含ActionBar
        slidingMenu.setOffsetFadeDegree(0.4f);
        slidingMenu.setMenu(R.layout.fragment_left_menu);
        //替换掉菜单内容
        getSupportFragmentManager().beginTransaction().replace(R.id.ll_leftmune, new Fragment_mune(), LEFT_MENU).commit();

    }

    //打开或者关闭侧滑菜单
    public void openorclose() {

        if (null != slidingMenu) {

            slidingMenu.toggle();
        }

    }

    //双击退出
    private long temptime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //重写了Menu监听，实现按下手机Menu键弹出和关闭侧滑菜单
        if (keyCode == KeyEvent.KEYCODE_MENU) {

            slidingMenu.toggle();

        } else if ((keyCode == KeyEvent.KEYCODE_BACK) && (event.getAction() == KeyEvent.ACTION_DOWN)) {

            //双击退出
            if (System.currentTimeMillis() - temptime > 2000) // 2s内再次选择back键有效
            {
                Toast.makeText(getApplicationContext(), "请在按一次返回退出", Toast.LENGTH_SHORT).show();
                temptime = System.currentTimeMillis();

            } else {

                finish();
                //  System.exit(0); //凡是非零都表示异常退出!0表示正常退出!
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        AppManager.getAppManager().addActivity(this);

        setSwipeBackEnable(false);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

//        AppManager.getAppManager().finishActivity(this);

    }



    /**
     * 得到左侧菜单
     *
     * @return
     */
    public Fragment_mune getLeftMenuFragment() {

        FragmentManager fm = getSupportFragmentManager();
        Fragment_mune leftMenuFragment = (Fragment_mune) fm.findFragmentByTag(LEFT_MENU);
        return leftMenuFragment;
    }

    @Override
    protected void onResume() {
        super.onResume();

        refreshLogInfo();
    }

    /*小米推送*/

    public void refreshLogInfo() {

        String AllLog = "";
        for (String log : logList) {

            AllLog = AllLog + log + "\n\n";
        }
    }

    /**
     * show the dialog when user logged into another device
     */
    public void showConflictDialog(String tichu) {

//        String st = getResources().getString(R.string.Logoff_notification);
        if (!HomeActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (conflictBuilder == null)

                    conflictBuilder = new AlertDialog.Builder(HomeActivity.this);
//              conflictBuilder.setTitle(st);
                conflictBuilder.setMessage(tichu);
                conflictBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                        //员工id
                        SharedPreferencesUtil.saveString(HomeActivity.this, "usersysno", "");
                        conflictBuilder = null;
                        finish();
                        Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
                conflictBuilder.setCancelable(false);
                conflictBuilder.create().show();

            } catch (Exception e) {
                Log.e(TAG, "---------color conflictBuilder error" + e.getMessage());
            }

        }
    }
}
